

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using System.IO;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store.Web.Controls;
using SubSonic.Utilities;

namespace JTC.MiniCommerce.Web.install.controls {
  public partial class database : AdminControl {

    #region Constants

    private const string SCRIPT_DROP = "~/install/scripts/drop.sql";
    private const string SCRIPT_TABLES = "~/install/scripts/tables.sql";
    private const string SCRIPT_FULL_TEXT_CATALOG = "~/install/scripts/fulltextcatalog.sql";
    private const string SCRIPT_FUNCTIONS = "~/install/scripts/functions.sql";
    private const string SCRIPT_VIEWS = "~/install/scripts/views.sql";
    private const string SCRIPT_SPS = "~/install/scripts/storedprocedures.sql";
    private const string SCRIPT_BASE_DATA = "~/install/scripts/basedata.sql";
    private const string SCRIPT_MEMBERSHIP_SCHEMA = "~/install/scripts/membership.sql";
    private const string SCRIPT_BASE_MEMBERSHIP_DATA = "~/install/scripts/basemembershipdata.sql";
    //private const string SCRIPT_SAMPLE_DATA = "~/install/scripts/SampleData.sql";

    #endregion
    
    #region Member Variables
  
    private int step = 0;
    
    #endregion
  
    protected void Page_Load(object sender, EventArgs e) {
      step = Utility.GetIntParameter("step");
      
      LocalizationUtility.AddPanelText(pnlDatabaseSetup);
      LocalizationUtility.AddLabelText(lblDatabaseInstructions);
      LocalizationUtility.AddHoverHelp(hlDatabaseServerHelp);
      LocalizationUtility.AddLabelText(lblDatabaseServer);
      LocalizationUtility.AddLabelText(lblDatabaseName);
      LocalizationUtility.AddHoverHelp(hlDatabaseNameHelp);
      LocalizationUtility.AddLabelText(lblDatabaseUserName);
      LocalizationUtility.AddHoverHelp(hlDatabaseUserNameHelp);
      LocalizationUtility.AddLabelText(lblDatabasePassword);
      LocalizationUtility.AddHoverHelp(hlDatabasePasswordHelp);
      LocalizationUtility.AddRfvErrorMessageText(rfvDatabaseServer);
      LocalizationUtility.AddRfvErrorMessageText(rfvDatabaseName);
      LocalizationUtility.AddRfvErrorMessageText(rfvDatabaseUserName);
      LocalizationUtility.AddRfvErrorMessageText(rfvDatabasePassword);
      LocalizationUtility.AddButtonText(btnNext);
      LocalizationUtility.AddButtonText(btnPrevious);  
    
    }

    protected void btnNext_Click(object sender, EventArgs e) {
      try {
        string connectionString = GetConnectionString();
        Session["ConnectionString"] = connectionString;
        RunScripts(connectionString);
        Response.Redirect(string.Format("~/install/install.aspx?step={0}", step + 1));
      }
      catch(Exception ex) {
        MasterPage.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    protected void btnPrevious_Click(object sender, EventArgs e) {
      try {
      Response.Redirect(string.Format("~/install/install.aspx?step={0}", step - 1), true);
      }
      catch(Exception ex) {
        MasterPage.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    private string GetConnectionString() {
			return string.Format("data source={0};Integrated Security=SSPI;Initial Catalog={1};user id={2};Password={3};",
				txtDatabaseServer.Text.Trim(),
				txtDatabaseName.Text.Trim(),
				txtDatabaseUserName.Text.Trim(),
				txtDatabasePassword.Text.Trim());
			// "data source=localhost;Integrated Security=SSPI;Initial Catalog=MiniCommerce"    

			//return string.Format("Server={0};Initial Catalog={1};user id={2};Password={3};", 
			//  txtDatabaseServer.Text.Trim(), 
			//  txtDatabaseName.Text.Trim(), 
			//  txtDatabaseUserName.Text.Trim(), 
			//  txtDatabasePassword.Text.Trim());      
    }

    private void RunScripts(string connectionString) {
      //Drop
      string[] dropStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_DROP), new System.Text.UTF8Encoding()));
      ExecuteStatements(dropStatements, connectionString);
      //Tables
      string[] tableStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_TABLES), new System.Text.UTF8Encoding()));
      ExecuteStatements(tableStatements, connectionString);
      //Full Text Catalog
      string[] fullTextStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_FULL_TEXT_CATALOG), new System.Text.UTF8Encoding()));
      ExecuteStatements(fullTextStatements, connectionString);
      //Functions
      string[] functionStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_FUNCTIONS), new System.Text.UTF8Encoding()));
      ExecuteStatements(functionStatements, connectionString);
      //Views
      string[] viewStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_VIEWS), new System.Text.UTF8Encoding()));
      ExecuteStatements(viewStatements, connectionString);
      //Stored Procedures
      string[] storedProcedureStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_SPS), new System.Text.UTF8Encoding()));
      ExecuteStatements(storedProcedureStatements, connectionString);
      //Base Data
      string[] baseDataStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_BASE_DATA), new System.Text.UTF8Encoding()));
      ExecuteStatements(baseDataStatements, connectionString);
      //Membership
      string[] membershipStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_MEMBERSHIP_SCHEMA), new System.Text.UTF8Encoding()));
      ExecuteStatements(membershipStatements, connectionString);
      //Base Membership Data
      string[] baseMembershipDataStatements = GetScriptStatements(File.ReadAllText(Server.MapPath(SCRIPT_BASE_MEMBERSHIP_DATA), new System.Text.UTF8Encoding()));
      ExecuteStatements(baseMembershipDataStatements, connectionString);
    }

    private string[] GetScriptStatements(string p) {
      string[] statements = p.Split(new string[] { "GO\r\n" }, StringSplitOptions.RemoveEmptyEntries);
      return statements;
    }

    private void ExecuteStatements(string[] statements, string connectionString) {
      if(statements.Length > 0) {
        using(SqlConnection conn = new SqlConnection()) {
          conn.ConnectionString = connectionString;
          conn.Open();
          using(SqlCommand command = new SqlCommand(string.Empty, conn)) {
            foreach(string statement in statements) {
              command.CommandText = statement;
              command.ExecuteNonQuery();
            }
          }
        }
      }
    }

    
    
  }
}